package ve.lm.hrms_cy.Service;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import ve.lm.hrms_cy.Entity.Announcement;
import ve.lm.hrms_cy.Entity.Employee;
import ve.lm.hrms_cy.Entity.Request.AnnouncementQueryRequest;
import ve.lm.hrms_cy.Entity.Request.RequestBillQueryRequest;
import ve.lm.hrms_cy.Entity.RequestBill;
import ve.lm.hrms_cy.Entity.Response.ResponseEntityCY;
import ve.lm.hrms_cy.Mapper.AnnouncementMapper;
import ve.lm.hrms_cy.Mapper.EmployeeMapper;
import ve.lm.hrms_cy.Mapper.RequestBillMapper;

import java.time.LocalDateTime;
import java.util.Optional;

@Service
public class CheckManagerService {

    @Autowired
    AnnouncementMapper announcementMapper;

    @Autowired
    EmployeeMapper employeeMapper;

    @Autowired
    RequestBillMapper requestBillMapper;

    public ResponseEntityCY<Boolean> addAnnouncement(Announcement announcement) {
        // 自动分配主键 ID（最大值 + 1）
        Long maxId = Optional.ofNullable(
                announcementMapper.selectList(null)
                        .stream()
                        .map(Announcement::getId)
                        .max(Long::compareTo)
                        .orElse(0L)
        ).orElse(0L);
        announcement.setId(maxId + 1);

        // 设置创建时间为当前时间（如果未传）
        if (announcement.getCreateTime() == null) {
            announcement.setCreateTime(LocalDateTime.now());
        }

        // 插入公告记录
        int row = announcementMapper.insert(announcement);
        if (row > 0) {
            return new ResponseEntityCY<>("200", true, true, "公告添加成功！");
        }
        return new ResponseEntityCY<>("500", false, false, "在可添加情况下出现未知错误！");
    }

    public ResponseEntityCY<IPage<Announcement>> findAnnouncementByPage(AnnouncementQueryRequest request) {
        LambdaQueryWrapper<Announcement> queryWrapper = new LambdaQueryWrapper<>();
        Page<Announcement> page = new Page<>(request.getCurrent(), request.getSize());

        // 精准查询 ID
        if (request.getId() != null) {
            queryWrapper.eq(Announcement::getId, request.getId());
        }

        // 时间范围查询（startTime 和 endTime 需转换为 LocalDateTime）

        if (request.getStartTime() != null && !request.getStartTime().isEmpty()) {

            queryWrapper.ge(Announcement::getCreateTime, request.getStartTime());
        }

        if(request.getStatus()!=null){

            queryWrapper.eq(Announcement::getStatus , request.getStatus());

        }


        if (request.getEndTime() != null && !request.getEndTime().isEmpty()) {
            queryWrapper.le(Announcement::getCreateTime, request.getEndTime());
        }

        return new ResponseEntityCY<>("200", true, announcementMapper.selectPage(page, queryWrapper), "成功查询公告信息！");
    }

    public ResponseEntityCY<Boolean> updateAnnouncement(Announcement announcement) {
        // 1. 校验是否存在
        Announcement existing = announcementMapper.selectById(announcement.getId());
        if (existing == null) {
            return new ResponseEntityCY<>("400", false, true, "未能找到该公告记录！");
        }

        // 2. 修改公告内容与状态
        int rows = announcementMapper.updateById(announcement);
        if (rows > 0) {
            return new ResponseEntityCY<>("200", true, true, "公告更新成功！");
        }
        return new ResponseEntityCY<>("500", false, false, "公告更新失败！");
    }

    public ResponseEntityCY<Boolean> addRequestBill(RequestBill bill) {
        // 1. 验证 employeeId 是否有效
        Employee emp = employeeMapper.selectById(bill.getEmployeeId());
        if (emp == null) {
            return new ResponseEntityCY<>("400", false, false, "未找到对应的申请主体！");
        }

        // 2. 自动设置主键 ID（最大 +1）
        Long maxId = requestBillMapper.selectList(null).stream()
                .map(RequestBill::getId)
                .max(Long::compareTo)
                .orElse(0L);
        bill.setId(maxId + 1);

        // 3. 设置创建时间
        bill.setCreateTime(LocalDateTime.now());

        // 4. 若状态不为“待审批”，将 checkId 设置为 userId
        if (!"待审批".equals(bill.getStatus())) {
            bill.setCheckId(bill.getUserId());
        }

        // 5. 插入
        int inserted = requestBillMapper.insert(bill);
        if (inserted > 0) {
            return new ResponseEntityCY<>("200", true, true, "成功添加申请！");
        }

        return new ResponseEntityCY<>("500", false, false, "添加申请失败！");
    }


    public ResponseEntityCY<IPage<RequestBill>> findRequestBillByPage(RequestBillQueryRequest request) {
        LambdaQueryWrapper<RequestBill> wrapper = new LambdaQueryWrapper<>();

        if (request.getId() != null) {
            wrapper.eq(RequestBill::getId, request.getId());
        }

        if (request.getUserId() != null) {
            wrapper.eq(RequestBill::getUserId, request.getUserId());
        }

        if (request.getStartTime() != null && request.getEndTime() != null) {
            wrapper.between(RequestBill::getCreateTime, request.getStartTime(), request.getEndTime());
        }

        if(request.getStatus()!=null)
            wrapper.eq(RequestBill::getStatus , request.getStatus());

        Page<RequestBill> page = new Page<>(request.getCurrent(), request.getSize());


        return new ResponseEntityCY<>("200", true, requestBillMapper.selectPage(page, wrapper), "查询成功！");
    }

    public ResponseEntityCY<Boolean> updateRequestBill(RequestBill bill) {
        RequestBill existing = requestBillMapper.selectById(bill.getId());
        if (existing == null) {
            return new ResponseEntityCY<>("404", false, true, "未找到该申请记录！");
        }

        // 申请主体验证
        Employee emp = employeeMapper.selectById(bill.getEmployeeId());
        if (emp == null) {
            return new ResponseEntityCY<>("400", false, true, "申请主体ID无效！");
        }

        // 设置审批者Id逻辑
        if (!"待审批".equals(bill.getStatus())) {
            bill.setCheckId(bill.getUserId());
        }

        int updated = requestBillMapper.updateById(bill);
        if (updated > 0) {
            return new ResponseEntityCY<>("200", true, true, "更新成功！");
        }

        return new ResponseEntityCY<>("500", false, false, "更新失败！");
    }

}
